package com.hxd.otc.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;

import com.alibaba.wireless.security.jaq.JAQException;
import com.alibaba.wireless.security.jaq.SecurityInit;
import com.hxd.otc.BuildConfig;
import com.hxd.otc.R;
import com.hxd.otc.common.HostType;
import com.hxd.otc.main.WelcomeActivity;
import com.hxd.otc.other.ActivityLifecycleCallbacksAdapter;
import com.hxd.otc.other.rong.OrderInfoFloatingMessage;
import com.hxd.otc.other.rong.OrderInfoFloatingMessageItemProvider;
import com.hxd.otc.other.rong.OrderInfoMessage;
import com.hxd.otc.other.rong.OrderInfoMessageItemProvider;
import com.hxd.otc.other.rong.RongUserInfoProvider;
import com.hxd.otc.utils.LogUtils;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.utils.hyphenate.HyphenateKeFuUtil;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.lang.ref.SoftReference;

import cat.ereza.customactivityoncrash.CustomActivityOnCrash;
import cat.ereza.customactivityoncrash.config.CaocConfig;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;

/**
 * 作  者 :  胡庆岭
 * 时  间 :  2018/4/25 12:14
 */
public class BaseApplication extends MultiDexApplication {

    public static BaseApplication mApp;

    public static int SERVER_HOST;

    public static boolean isHideZeroAssests;

    public static String mLocal = "zh";
    private SoftReference<Activity> mTopActivitySoftReference;

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    public static String getLocal() {
        return mLocal;
    }

    public static void setLocal(String local) {
        BaseApplication.mLocal = local;
    }

    public static int getServerHost() {
        return SERVER_HOST;
    }

    public static BaseApplication getInstance() {
        return mApp;
    }


    @SuppressLint("RestrictedApi")
    private void init() {
        mApp = this;

        SERVER_HOST = BuildConfig.API_SERVER_URL;
//        SERVER_HOST = HostType.HOST_FORMAL;
        MultiDex.install(this);

        initRongIM();

        //初始化友盟
        initUMeng();
        //获取上下文
        UIUtils.init(this);
        //内存泄漏检测
        initLeakCanary();
        //崩溃信息检测
        initCaocConfig();
        //二维码
        ZXingLibrary.initDisplayOpinion(this);

        if (!BuildConfig.isDebug) {
            CrashReport.initCrashReport(getApplicationContext(), "4fd3701d39", BuildConfig.DEBUG);
        }

        //环信客服
        initHyphenateKeFu();

        registerActivityLifecycleCallbacks();//获取获取栈顶activity实例

        try {
            //0：初始化成功   1：初始化失败
            int aliData = SecurityInit.Initialize(this);
            LogUtils.e("aliData====" + aliData);
        } catch (JAQException e) {
            e.printStackTrace();
        }
    }

    /**
     * 环信客服
     */
    private void initHyphenateKeFu() {
        HyphenateKeFuUtil.getInstance().initHyphenateKeFu();
    }


    private void initRongIM() {
        RongIM.init(this);
        RongIM.registerMessageType(OrderInfoMessage.class);
        RongIM.registerMessageType(OrderInfoFloatingMessage.class);
        RongIM.registerMessageTemplate(new OrderInfoMessageItemProvider());
        RongIM.registerMessageTemplate(new OrderInfoFloatingMessageItemProvider());
        Conversation.ConversationType[] types = new Conversation.ConversationType[]{
                Conversation.ConversationType.PRIVATE,
        };
        RongIM.getInstance().setReadReceiptConversationTypeList(types);
        RongIM.setUserInfoProvider(new RongUserInfoProvider(), true);
    }

    private void initCaocConfig() {
        CaocConfig.Builder.create()
                .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //default: CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM
                .enabled(true) //default: true
                .showErrorDetails(true) //default: true
                .showRestartButton(true) //default: true
                .logErrorOnRestart(true) //default: true
                .trackActivities(false) //default: false
                .minTimeBetweenCrashesMs(2000) //default: 3000
                .restartActivity(WelcomeActivity.class) //default: null (your app's launch activity)
                .errorActivity(WelcomeActivity.class) //default: null (default error activity)
                .eventListener(new EventListener())
                .apply();
    }

    private void initUMeng() {
        UMConfigure.setLogEnabled(BuildConfig.DEBUG);
        UMConfigure.init(this, "5b9f14768f4a9d1cbc000147", "Umeng", UMConfigure.DEVICE_TYPE_PHONE, null);
        PlatformConfig.setWeixin("wxf76ea8a2527e44fb", "82a88264658c5179165b483263c86b29");
        PlatformConfig.setQQZone("101510555", "46df2ffcf4af61386b716014c5f5fc8d");
    }

    public void initLeakCanary() {
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);
    }

    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.colorAccent, android.R.color.white);//全局设置主题颜色
                return new MaterialHeader(context).setShowBezierWave(false);
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    public void registerActivityLifecycleCallbacks() {
        this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacksAdapter() {

            @Override
            public void onActivityStarted(Activity activity) {
                mTopActivitySoftReference = new SoftReference<>(activity);
            }
        });
    }

    public Activity getTopActivity() {
        if (mTopActivitySoftReference != null) {
            return mTopActivitySoftReference.get();
        }
        return null;
    }


    public static class EventListener implements CustomActivityOnCrash.EventListener {

        @Override
        public void onLaunchErrorActivity() {

        }

        @Override
        public void onRestartAppFromErrorActivity() {

        }

        @Override
        public void onCloseAppFromErrorActivity() {

        }
    }

}
